#include "queue_s.h"

int CSafeQueue::Init(int iMax)
{
    m_clSem.Init(iMax);
    return 0;
}

int CSafeQueue::Recycle()
{
    m_clSem.Recycle();
    Destruct();
    return Construct();
}

int CSafeQueue::Push(void* pvData)
{
    int iResult, iTmp;

    m_objLock.lock();
    m_objQueue.push(pvData);
    m_objLock.unlock();
    iResult = m_clSem.Send();
    return 0;
}

int CSafeQueue::Pop(OUT void*& pvData, int iTimeout)
{
    int iRet = -1;
    int iResult, iTmp;

    iResult = m_clSem.Recv(iTimeout);
    if(iResult < 0) SET_RET_AND_GOTO_EXIT(iResult);

    m_objLock.lock();
    pvData = m_objQueue.front();
    m_objQueue.pop();
    m_objLock.unlock();

    iRet = 0;
_Exit:
    return iRet;
}

int CSafeQueue::PopAll(STD_ARRAY<void*>* pobjOut)
{
    int iResult, iTmp;
    void* p = nullptr;

    m_objLock.lock();
    while(m_objQueue.size() > 0)
    {
        iResult = m_clSem.Recv(0);
        if(iResult < 0) break;

        p = m_objQueue.front();
        m_objQueue.pop();

        if(pobjOut) pobjOut->push_back(p);
    }
    m_objLock.unlock();
    return 0;
}

int CSafeQueue::Destruct()
{
    Clear();
    return 0;
}
